//
//  NewSellerAllRecordViewController.m
//  智积分
//
//  Created by Cynic on 2018/8/3.
//  Copyright © 2018年 Cynic. All rights reserved.
//

#import "NewSellerAllRecordViewController.h"
#import "NewSellerOrderScrollTableViewCell.h"
#import "NewSellerPersonlistTableViewCell.h"
#import "DetailCodeStoreOrderViewController.h"
#import "RecordTimePickerViewController.h"
#import "NewSellerShortOrdersTableViewCell.h"
#import "DetailOrderInfoViewController.h"
#import "DealInfoViewController.h"//jump int detailinfo

static NSString *firstnewsellerorderscrollcellIndentifier = @"firstnewsellerorderscrollcellIndentifier";
static NSString *firstnewsellerorderPersonlistcellindentifier = @"firstnewsellerorderPersonlistcellindentifier";
static NSString *secondnewsellerorderscrollcellIndentifier = @"secondnewsellerorderscrollcellIndentifier";
static NSString *NewSellerShortOrdersTableViewCellindentifier = @"NewSellerShortOrdersTableViewCellindentifier";

@interface NewSellerAllRecordViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,retain)UITableView *MainView;
@property (nonatomic ,retain)NSDictionary *moneyDataLoad;
@property (nonatomic ,retain)NSMutableDictionary *moneyData;//门店营业额数据
@property (nonatomic ,retain)NSMutableArray *buylist;//首页数据列表
@property (nonatomic ,assign)BOOL FirstLoaded;
//@property (nonatomic ,retain)UIView *headerPersonlistview;
@property (nonatomic ,assign)NSInteger currentFirstPgae;
@property (nonatomic ,strong)NSMutableArray *realData;
@property (nonatomic ,assign)NSInteger type;
@end

@implementation NewSellerAllRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

-(instancetype)initWithtype:(NSInteger)type{
    self = [super init];
    _type = type;
    _buylist = [NSMutableArray array];
    _realData = [NSMutableArray array];
    [self viewLoad];
    self.view.backgroundColor = bggrayColor;
    [self.MainView.mj_header beginRefreshing];
    return self;
}


-(void)viewLoad{
    _FirstLoaded = NO;
    [self setNavigationViewWithTitle:@"历史明细" WithCanPop:YES WithPopData:@"return" WithPopisString:NO WithHasRightOperation:NO WithrightOperationData:@"筛选" WithRightisString:YES WithNavigationColor:BaseColor withBgView:self.view];
    [self.navigationView AddColorsFrom:[UIColor ColorWithHex:@"#FF7F5A" withAlpha:1] ToEndColor:[UIColor ColorWithHex:@"#FE4438" withAlpha:1]];
    [self.navigationView bringSubviewToFront:self.popButton];
    [self.navigationView bringSubviewToFront:self.centerTitle];
    [self.navigationView bringSubviewToFront:self.rightOperationButton];
    [self.view addSubview:self.MainView];
}

-(UITableView *)MainView{
    if(!_MainView){
        _MainView = [[UITableView alloc] initWithFrame:CGRectMake(cx_wid * 0, cxsingler.topdis + 44, cx_wid, cx_hit - cxsingler.topdis - 44 -cxsingler.bottomdis)];
        [_MainView placeImageWithData:@"404" withOffset:100];
        _MainView.placeImageView.hidden = YES;
        _MainView.backgroundColor = bggrayColor;
        
        _MainView.estimatedRowHeight = 0;
        if (@available(iOS 11.0, *)) {
            _MainView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _MainView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _MainView.backgroundColor = [CXSinglerModel colorWithHex:@"f3f4f6" alpha:1];
        _MainView.delegate = self;
        _MainView.dataSource = self;
        if (_type == 0) {
        [_MainView registerClass:[NewSellerOrderScrollTableViewCell class] forCellReuseIdentifier:firstnewsellerorderscrollcellIndentifier];
        [_MainView registerClass:[NewSellerPersonlistTableViewCell class] forCellReuseIdentifier:firstnewsellerorderPersonlistcellindentifier];
        }
        else{
            [_MainView registerClass:[NewSellerOrderScrollTableViewCell class] forCellReuseIdentifier:secondnewsellerorderscrollcellIndentifier];
            [_MainView registerClass:[NewSellerShortOrdersTableViewCell class] forCellReuseIdentifier:NewSellerShortOrdersTableViewCellindentifier];
        }
        WEAKSELF;
        MJRefreshGifHeader *Gifheader = [MJRefreshGifHeader headerWithRefreshingBlock:^{
                        if (weakSelf.type == 0) {
                            [weakSelf moneyDataLoad];}
                        else{
                            [self storeMoneyLoad];
                        }
            [weakSelf buylistLoadWithmore:NO];
            
        }];
        MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            //            if (segnum == 0){
            [weakSelf buylistLoadWithmore:YES];
            //            }
            //            else if (segnum == 1){
            //                [weakSelf StoreOrderListLoadWithmore:YES];
            //            }
            //            else if (segnum == 2){
            //                if(cxsingler.sellersegnum > 2){
            //                    [weakSelf CodeOrderListLoadWithMore:YES];
            //                }
            //            }
        }];
        [Gifheader setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
        [Gifheader setTitle:@"松开刷新" forState:MJRefreshStatePulling];
        [Gifheader setTitle:@"刷新中……" forState:MJRefreshStateRefreshing];
        [footer setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
        [footer setTitle:@"松开加载更多" forState:MJRefreshStatePulling];
        [footer setTitle:@"加载更多中……" forState:MJRefreshStateRefreshing];
        _MainView.mj_header = Gifheader;
        _MainView.mj_footer = footer;
    }
    return _MainView;
}


#pragma mark--tableview代理开始
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1 + _realData.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    else{
        if (_buylist.count == 0 && _FirstLoaded) {
            tableView.placeImageView.hidden = NO;
        }
        else{
            tableView.placeImageView.hidden = YES;
        }
        return [_realData[section - 1] count];
    }
    
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger sec = indexPath.section;
        NSInteger row = indexPath.row;
    if (sec == 0) {
        return cx_wid / 378 * 185 + 10;
    }
    if (_type == 0) {
        return 54;
    }
    else if (_type == 1){
        NSInteger num = [_realData[sec - 1][row][@"order_lst"] count];
        return 150 + num * 84;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section > 0) {
        return 44;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section > 0) {
//        if (!_headerPersonlistview) {
            UIView *headerPersonlistview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cx_wid, 44)];
            headerPersonlistview.backgroundColor = [UIColor whiteColor];
            UILabel *timelabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 14, 140, 16)];
            UIButton *deslabel = [[UIButton alloc] initWithFrame:CGRectMake(cx_wid - 12 - 60, 14,60, 16)];
            deslabel.hidden = YES;
            WEAKSELF;
            [deslabel cx_eventsBlockHandler:^{
                NewSellerAllRecordViewController *nextVC = [[NewSellerAllRecordViewController alloc] init];
                [weakSelf.navigationController pushViewController:nextVC animated:YES];
            } forControlEvents:UIControlEventTouchUpInside];
        NSString *timestr = @"";
        if (_type == 0) {
            timestr = [self gettimeByInter:[[[NSString stringWithFormat:@"%@",_realData[section - 1][0][@"createTime"]] substringWithRange:NSMakeRange(0, 10)] integerValue]];
        }
        else if (_type == 1){
            timestr = [[NSString stringWithFormat:@"%@",_realData[section - 1][0][@"create_time"]] substringToIndex:10];
        }
        
        timelabel.text = timestr.length > 10 ? [timestr substringToIndex:10] : timestr;
            [deslabel setTitle:@"对账" forState:UIControlStateNormal];
            deslabel.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            timelabel.font = [UIFont systemFontOfSize:15];
            deslabel.titleLabel.font = [UIFont systemFontOfSize:15];
            [deslabel setTitleColor:[CXSinglerModel colorWithHex:@"999999" alpha:1] forState:UIControlStateNormal];
            timelabel.textColor = [UIColor blackColor];
            UIView *layerview = [[UIView alloc] initWithFrame:CGRectMake(0, 43, cx_wid, 1)];
            layerview.backgroundColor = [CXSinglerModel colorWithHex:@"f3f4f6" alpha:1];
            [headerPersonlistview addSubview:layerview];
            [headerPersonlistview addSubview:timelabel];
            [headerPersonlistview addSubview:deslabel];
        return headerPersonlistview;
    }
    UIView *nilview = [[UIView alloc] initWithFrame:CGRectZero];
    return nilview;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    NSInteger sec = indexPath.section;
    if (_type == 1) {
        if (sec == 0) {
            NewSellerOrderScrollTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:secondnewsellerorderscrollcellIndentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.money.text = [NSString stringWithFormat:@"%.2lf",([[self Nnll:_moneyData[@"total_integral"] withPlace:@"0"] floatValue] + [[self Nnll:_moneyData[@"total_cash"] withPlace:@"0"] floatValue]) / 100];
            cell.ordersNum.text = [NSString stringWithFormat:@"%@",[self Nnll:_moneyData[@"trade_cnt"] withPlace:@"0"]];
            cell.dealsNum.text = [NSString stringWithFormat:@"%@",[self Nnll:_moneyData[@"total_goods"] withPlace:@"0"]];
            cell.TodayRiseCode.text = [NSString stringWithFormat:@"%ld",[[self Nnll:_moneyData[@"total_integral"] withPlace:@"0"] integerValue]];
            cell.TodayRiseMoney.text = [NSString stringWithFormat:@"%.2lf",([[self Nnll:_moneyData[@"total_cash"] withPlace:@"0"] floatValue]) / 100];
            return cell;
        }
        else {
            NSDictionary *part = _realData[sec - 1][row];
            NewSellerShortOrdersTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NewSellerShortOrdersTableViewCellindentifier];
            cell.clipsToBounds = YES;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if ([part[@"parent_order_id"] isEqual:@"EA8352087"]) {
                
            }
            cell.time.text = part[@"create_time"];
            cell.ordernum.text = part[@"parent_order_id"];
            cell.buyyer.text = [NSString stringWithFormat:@"买家:%@",part[@"nickname"]];
            cell.status.text = part[@"order_lst"][0][@"delive_goods_status_str"];
            [cell loadProductions:part[@"order_lst"]];
            //            cell.productionname.text = part[@"order_lst"][0][@"goods_name"];
            //            cell.productioninfo.text = part[@"order_lst"][0][@"goods_attr"];
            //            cell.num.text = part[@"goods_num"];
            //            [cell.productionimg sd_setImageWithURL:[NSURL URLWithString:part[@"order_lst"][0][@"goods_sm_img"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"logo2"]];
            NSString *transmoney = @"免费";
            if ([part[@"mix_all_freight_price"] floatValue] > 0) {
                transmoney = [NSString stringWithFormat:@"%.2lf",[part[@"mix_all_freight_price"] floatValue] / 100];
            }
            cell.transMoney.text = [NSString stringWithFormat:@"%@",transmoney];
            
            NSString *price = [NSString stringWithFormat:@"%.2lf",([part[@"payment_details"][@"pay_amount"] floatValue] + [part[@"payment_details"][@"pay_integral"] floatValue]) / 100];
            NSInteger count = 0;
            for (NSDictionary *dic in part[@"order_lst"]) {
                count = count + [dic[@"goods_num"] integerValue];
            }
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"共%ld件,合计:￥%@",count,price]];
            [str addAttribute:NSForegroundColorAttributeName value:[CXSinglerModel colorWithHex:@"666666" alpha:1] range:NSMakeRange(0,str.length)];
            [str addAttribute:NSForegroundColorAttributeName value:[CXSinglerModel colorWithHex:@"#FE4438" alpha:1] range:NSMakeRange(str.length - price.length - 1,price.length + 1)];
            cell.costmoney.attributedText = str;
            
            return cell;
        }
        
    }
    if (sec == 0) {
        NewSellerOrderScrollTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:firstnewsellerorderscrollcellIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.money.text = [NSString stringWithFormat:@"%.2lf",[_moneyData[@"totalAmount"] floatValue] / 100];
        cell.ordersNum.text = [NSString stringWithFormat:@"%ld",[_moneyData[@"orderCount"] integerValue]];
        cell.dealsNum.text = [NSString stringWithFormat:@"%ld",[_moneyData[@"userCount"] integerValue]];
        cell.TodayRiseCode.text = [NSString stringWithFormat:@"%ld",[[self Nnll:_moneyData[@"balanceArrived"] withPlace:@"0"] integerValue]];
        cell.TodayRiseMoney.text = [NSString stringWithFormat:@"%.2lf",([[self Nnll:_moneyData[@"bankArrived"] withPlace:@"0"] floatValue]) / 100];
        return cell;
    }
    else {
        NSMutableDictionary *part = _realData[sec - 1][row];
        NewSellerPersonlistTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:firstnewsellerorderPersonlistcellindentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.name.text =  part[@"userName"];;
        cell.time.text = [self gettimeByInter:[[[NSString stringWithFormat:@"%@",part[@"createTime"]] substringWithRange:NSMakeRange(0, 10)] integerValue]];
        cell.money.text = [NSString stringWithFormat:@"+%.2lf",[part[@"price"] floatValue] / 100];
        [cell.header sd_setBackgroundImageWithURL:[NSURL URLWithString:part[@"avatar"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"logo1"]];
        return cell;
    }
    
    return nil;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    NSInteger sec = indexPath.section;
    if (sec > 0) {
    if (_type == 0) {
            NSMutableDictionary *part = _realData[sec - 1][row];
        DealInfoViewController *nextVC = [[DealInfoViewController alloc] init];
        [nextVC loadWithInfo:part];
        [self.navigationController pushViewController:nextVC animated:YES];
    }
    else if (_type == 1){
        DetailOrderInfoViewController *nextvc = [[DetailOrderInfoViewController alloc] initWithData:_realData[sec - 1][row]];
        [self.navigationController pushViewController:nextvc animated:YES];
    }
    }
}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if ([scrollView isEqual:_BGScroll]) {
//        CGFloat contentwid = scrollView.contentOffset.x;
//        _noticeView.frame = CGRectMake(contentwid / cxsingler.sellersegnum, 31, cx_wid / cxsingler.sellersegnum, 3);
//        NSInteger roundnum = roundf(contentwid / cx_wid);
//        if (roundnum != _currentSegNum) {
//            _currentSeg.selected = NO;
//            _currentSeg = [_segs objectAtIndex:roundnum];
//            _currentSeg.selected = YES;
//            _currentSegNum = roundnum;
//        }
//    }
//}


#pragma mark--tableview代理结束

#pragma mark--数据加载
#pragma mark--消费列表获取//门店
-(void)buylistLoadWithmore:(BOOL)more{
    NSInteger currentpage = 0;
    [SVProgressHUD showWithStatus:@"加载中"];
    NetWorkModel *netmodel = [[NetWorkModel alloc] init];
    if (!more) {
        currentpage = _currentFirstPgae = 1;
    }
    else{
        currentpage = _currentFirstPgae + 1;
    }
    if (_type == 0) {
    [netmodel getStoreDetailBuessesswithpage:currentpage withOnlyToday:NO];
    }
    else if (_type == 1){
        [netmodel NewSellerStoreGetOrderlistByshopID:cxsingler.loginrequest[@"admin"][@"shop_id"] WithPage:currentpage withOnlyToday:NO];
    }
    WEAKSELF;
    netmodel.sendMessage = ^(NSString *result) {
        weakSelf.FirstLoaded = YES;
        if (more) {
            [[(UITableView *)weakSelf.MainView mj_footer] endRefreshing];
        }
        else{
            [[(UITableView *)weakSelf.MainView mj_header] endRefreshing];
        }
        if ([result isEqual:@"success"]) {
            [SVProgressHUD dismiss];
            NSArray *list = cxsingler.ArraryData;
            if (list.count > 0) {
                weakSelf.currentFirstPgae = currentpage;
                if (!more) {
                    weakSelf.buylist = [NSMutableArray array];
                }
                //                for (NSDictionary *dic in list) {
                //                    [weakSelf.buylist addObject:dic];
                //                }
                [weakSelf.buylist addObjectsFromArray:list];
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [weakSelf.MainView reloadData];
                    [weakSelf dataSet];
                });
            }
            else if (!more){
                weakSelf.currentFirstPgae = currentpage;
                weakSelf.buylist = [NSMutableArray array];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.MainView reloadData];
                });
            }
        }
        else{
            [SVProgressHUD showErrorWithStatus:result];
        }
    };
}



//-(void)StoreOrderListLoadWithmore:(BOOL)more{
//    NSInteger newpage = 0;
//    if (!more) {
//        newpage = _currentFirstPgae = 1;
//    }
//    else{
//        newpage = _currentFirstPgae + 1;
//    }
//    NetWorkModel *netmodel = [[NetWorkModel alloc] init];
//    [netmodel NewSellerStoreGetOrderlistByshopID:cxsingler.loginrequest[@"admin"][@"shop_id"] WithPage:newpage];
//    WEAKSELF;
//    netmodel.sendMessage = ^(NSString *result) {
//        weakSelf.FirstLoaded = YES;
////        UITableView *tableview = weakSelf.MainViews[1];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if ([weakSelf.MainView.mj_header isRefreshing]) {
//                [weakSelf.MainView.mj_header endRefreshing];
//            }
//            else if([weakSelf.MainView.mj_footer isRefreshing]){
//                [weakSelf.MainView.mj_footer endRefreshingWithCompletionBlock:^{
//
//                }];
//            }
//        });
//        if ([result isEqual:@"success"]) {
//            NSArray *resultList = cxsingler.ArraryData;
//            if(resultList.count > 0){
//                weakSelf.currentFirstPgae = newpage;
//            }
//            if (more) {
//                if (resultList.count > 0) {
//                    for (NSInteger index = 0; index < resultList.count; index ++) {
//                        [weakSelf.buylist addObject:resultList[index]];
//                    }
//                }
//            }
//            else{
//                if (resultList.count > 0) {
//                    weakSelf.buylist = [NSMutableArray array];
//                    weakSelf.buylist = [resultList mutableCopy];
//                }
//                else {
//                    weakSelf.currentSecondPage = newpage;
//                    weakSelf.shoporders = [NSMutableArray array];
//                }
//            }
//            [(UITableView *)[weakSelf.MainViews objectAtIndex:1] reloadData];
//        }
//        else{
//            [SVProgressHUD showErrorWithStatus:result];
//        }
//    };
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dataSet{
    _realData = [NSMutableArray array];
    NSString *timestr = @"";
    NSMutableArray *partList = [NSMutableArray array];
    for (NSDictionary *part in _buylist) {
        NSString *partTime = @"";
        if (_type == 0) {
         partTime = [[self gettimeByInter:[[[NSString stringWithFormat:@"%@",part[@"createTime"]] substringWithRange:NSMakeRange(0, 10)] integerValue]] substringToIndex:10];
        }
        if (_type == 1) {
            partTime = [[NSString stringWithFormat:@"%@",part[@"create_time"]] substringToIndex:10];
        }
        if([timestr length] == 0){
            [partList addObject:part];
        }
       else if(![timestr isEqual:partTime]){
            if(partList.count > 0){
                [_realData addObject:partList];
            }
            partList = [NSMutableArray array];
            [partList addObject:part];
        }
        else{
            [partList addObject:part];
        }
        timestr = partTime;
        if([part isEqual:_buylist.lastObject] && partList.count > 0){
            [_realData addObject:partList];
        }
    }
    [self.MainView reloadData];
}

#pragma mark--商店资金part
-(void)storeMoneyLoad{
    NetWorkModel *netmodel = [[NetWorkModel alloc] init];
    [netmodel NewSellerStoreMoneyinfowithShopID:cxsingler.loginrequest[@"admin"][@"shop_id"]];
    WEAKSELF;
    netmodel.sendMessage = ^(NSString *result) {
        if ([result isEqual:@"success"]) {
            weakSelf.moneyData = [cxsingler.DicData mutableCopy];
//            [weakSelf reloadMoneyWithSeg:1];
            [weakSelf.MainView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
        
    };
}

-(void)rightTped:(UIButton *)sender{
    RecordTimePickerViewController *nextVC = [[RecordTimePickerViewController alloc] init];
    [self.navigationController pushViewController:nextVC animated:YES];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
